<?
class Web {

	var $allow_unicode = 1;
	var $get_magic_quotes = 0;
	var $base_url = "";
	var $session_id = "";
	var $session_type;
	var $seller = array ();
	var $location = 0;
	var $nav_link = array ();
	var $cache_id;
	var $lang = '';
	var $tlang = '';
	var $lang_id = '';
	/*-------------------------------------------------------------------------*/
	// Makes incoming info "safe"              
	/*-------------------------------------------------------------------------*/

	function parse_incoming() {
		global $_GET, $_POST, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;
		$return = array ();

		if (is_array($_GET)) {
			while (list ($k, $v) = each($_GET)) {
				if (is_array($_GET[$k])) {
					while (list ($k2, $v2) = each($_GET[$k])) {
						$return[$k][$this->clean_key($k2)] = $this->clean_value($v2);
					}
				} else {
					$return[$k] = $this->clean_value($v);
				}
			}
		}

		// Overwrite GET data with post data

		if (is_array($_POST)) {
			while (list ($k, $v) = each($_POST)) {
				if (is_array($_POST[$k])) {
					while (list ($k2, $v2) = each($_POST[$k])) {
						$return[$k][$this->clean_key($k2)] = $this->clean_value($v2);
					}
				} else {
					$return[$k] = $this->clean_value($v);
				}
			}
		}

		//----------------------------------------
		// Sort out the accessing IP
		// (Thanks to Cosmos and schickb)
		//----------------------------------------

		$addrs = array ();

		foreach (array_reverse(explode(',', $HTTP_X_FORWARDED_FOR)) as $x_f) {
			$x_f = trim($x_f);

			if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f)) {
				$addrs[] = $x_f;
			}
		}

		$addrs[] = $_SERVER['REMOTE_ADDR'];
		$addrs[] = $HTTP_PROXY_USER;
		$addrs[] = $REMOTE_ADDR;

		//header("Content-type: text/plain"); print_r($addrs); print $_SERVER['HTTP_X_FORWARDED_FOR']; exit();

		$return['IP_ADDRESS'] = $this->select_var($addrs);

		// Make sure we take a valid IP address

		$return['IP_ADDRESS'] = preg_replace("/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS']);

		$return['request_method'] = ($_SERVER['REQUEST_METHOD'] != "") ? strtolower($_SERVER['REQUEST_METHOD']) : strtolower($REQUEST_METHOD);

		return $return;
	}

	/*-------------------------------------------------------------------------*/
	// Key Cleaner - ensures no funny business with form elements             
	/*-------------------------------------------------------------------------*/

	function clean_key($key) {

		if ($key == "") {
			return "";
		}
		$key = preg_replace("/\.\./", "", $key);
		$key = preg_replace("/\_\_(.+?)\_\_/", "", $key);
		$key = preg_replace("/^([\w\.\-\_]+)$/", "$1", $key);
		return $key;
	}
	function clean_value($val) {

		if ($val == "") {
			return "";
		}

		$val = str_replace("&#032;", " ", $val);

		$val = str_replace("&", "&amp;", $val);
		$val = str_replace("<!--", "&#60;&#33;--", $val);
		$val = str_replace("-->", "--&#62;", $val);
		$val = preg_replace("/<script/i", "&#60;script", $val);
		$val = str_replace(">", "&gt;", $val);
		$val = str_replace("<", "&lt;", $val);
		$val = str_replace("\"", "&quot;", $val);
		//$val = preg_replace( "/\n/"        , "<br>"          , $val ); // Convert literal newlines
		$val = preg_replace("/\\\$/", "&#036;", $val);
		//$val = preg_replace( "/\r/"        , ""              , $val ); // Remove literal carriage returns
		$val = str_replace("!", "&#33;", $val);
		$val = str_replace("'", "&#39;", $val); // IMPORTANT: It helps to increase sql query safety.

		// Ensure unicode chars are OK

		if ($this->allow_unicode) {
			$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val);
		}

		// Strip slashes if not already done so.

		if ($this->get_magic_quotes) {
			$val = stripslashes($val);
		}

		// Swop user inputted backslashes

		$val = preg_replace("/\\\(?!&amp;#|\?#)/", "&#092;", $val);

		return $val;
	}

	/*-------------------------------------------------------------------------*/
	// Variable chooser             
	/*-------------------------------------------------------------------------*/

	function select_var($array) {

		if (!is_array($array))
			return -1;

		ksort($array);

		$chosen = -1; // Ensure that we return zero if nothing else is available

		foreach ($array as $k => $v) {
			if (isset ($v)) {
				$chosen = $v;
				break;
			}
		}

		return $chosen;
	}

	function error($msg = "未知错误", $url = "") {
		$this->assign("msg_info", $msg);
		//$this -> assign("back_url",ROOT_PATH."index.php".$url);
		$this->output("Error.tpl");
	}

	/*------------------------------------------------------------------------*/
	// txt_stripslashes
	// ------------------
	// Make Big5 safe - only strip if not already...
	/*-------------------------------------------------------------------------*/

	function txt_stripslashes($t) {
		if ($this->get_magic_quotes) {
			$t = stripslashes($t);
		}

		return $t;
	}

	/*-------------------------------------------------------------------------*/
	// Sets a cookie, abstract layer allows us to do some checking, etc                
	/*-------------------------------------------------------------------------*/

	function my_setcookie($name, $value = "", $sticky = 1) {
		global $CONF;

		//$expires = "";

		if ($sticky == 1) {
			$expires = time() + 60 * 60 * 24 * 365;
		}

		$CONF['cookie_domain'] = $CONF['cookie_domain'] == "" ? "" : $CONF['cookie_domain'];
		$CONF['cookie_path'] = $CONF['cookie_path'] == "" ? "/" : $CONF['cookie_path'];

		$name = $CONF['cookie_id'] . $name;

		setcookie($name, $value, $expires, $CONF['cookie_path'], $CONF['cookie_domain']);
	}

	/*-------------------------------------------------------------------------*/
	// Cookies, cookies everywhere and not a byte to eat.                
	/*-------------------------------------------------------------------------*/

	function my_getcookie($name) {
		global $CONF, $HTTP_COOKIE_VARS;

		if (isset ($HTTP_COOKIE_VARS[$CONF['cookie_id'] . $name])) {
			return urldecode($HTTP_COOKIE_VARS[$CONF['cookie_id'] . $name]);
		} else {
			return FALSE;
		}

	}
	/*-------------------------------------------------------------------------*/
	// Delete buck of picture files on the server
	// make sure "buck of" means array!
	/*-------------------------------------------------------------------------*/
	function unlink_pic($file_name, $thumb = 0) {
		if (!is_array($file_name))
			return;
		foreach ($file_name as $v) {
			@ unlink($this->make_full_path($v, $thumb));
		}
		return;
	}
	function make_full_path($file_name, $thumb = 0) // mixed dir and url
	{
		global $CONF;
		$start = 5;
		if ($thumb)
			$start += strlen($CONF['thumb_prefix']);
		$timestamp = substr($file_name, $start, 10);
		return $CONF['upload_url'] . date("Y", $timestamp) . "/" . date("m", $timestamp) . "/" . $file_name;
	}

	function get_thumb($file_name) {
		global $CONF;

		$pathfile = $this->make_full_path($file_name);
		$thumbfile = $this->make_full_path($CONF['thumb_prefix'] . $file_name, 1);
		if (!@ is_file($thumbfile)) {
			$this->_resize($thumbfile, $pathfile, "php", "");
		}
		return $thumbfile;
	}
    function getThumb($pathfile)
	{
        $thumbfile = str_replace(".j","s.j",$file);
		if (!@ is_file($thumbfile)) {
			$this->_resize($thumbfile, $pathfile, "php", "");
		}
		return $thumbfile;
	}
	function redirect($url) {
		header("Location:$url");
		exit;
	}
	function build_pagelinks($data) {

		$work = array ();

		$section = ($data['leave_out'] == "") ? 2 : $data['leave_out']; // Number of pages to show per section( either side of current), IE: 1 ... 4 5 [6] 7 8 ... 10

		$work['pages'] = 1;

		if (($data['TOTAL_POSS'] % $data['PER_PAGE']) == 0) {
			$work['pages'] = $data['TOTAL_POSS'] / $data['PER_PAGE'];
		} else {
			$number = ($data['TOTAL_POSS'] / $data['PER_PAGE']);
			$work['pages'] = ceil($number);
		} //分多少页

		$work['total_page'] = $work['pages'];
		$work['current_page'] = $data['CUR_ST_VAL'] > 0 ? ($data['CUR_ST_VAL'] / $data['PER_PAGE']) + 1 : 1;

		if ($work['pages'] > 1) {
			$work['first_page'] = "分页：";

			for ($i = 0; $i <= $work['pages'] - 1; ++ $i) {
				$RealNo = $i * $data['PER_PAGE'];
				$PageNo = $i +1;

				if ($RealNo == $data['CUR_ST_VAL']) {
					$work['page_span'] .= "&nbsp;<b>[{$PageNo}]</b>";
				} else {

					if ($PageNo < ($work['current_page'] - $section)) {
						$work['st_dots'] = "&nbsp;<a href='{$data['BASE_URL']}&amp;st=0' title='首页'} 1'>&laquo; 首页</a>&nbsp;...";
						continue;
					}

					// If the next page is out of our section range, add some dotty dots!

					if ($PageNo > ($work['current_page'] + $section)) {
						$work['end_dots'] = "...&nbsp;<a href='{$data['BASE_URL']}&amp;st=" . ($work['pages'] - 1) * $data['PER_PAGE'] . "' title='总页数 {$work['pages']}'>末页 &raquo;</a>";
						break;
					}

					$work['page_span'] .= "&nbsp;<a href='{$data['BASE_URL']}&amp;st={$RealNo}'>{$PageNo}</a>";
				}
			}

			$work['return'] = $work['first_page'] . $work['st_dots'] . $work['page_span'] . '&nbsp;' . $work['end_dots'];
		} else {
			$work['return'] = $data['L_SINGLE'];
		}

		return $work['return'];
	}

	function do_nav_link() {
		foreach ($this->nav_link as $k => $v) {
			if (!$k) {
				$link_str = "<a href='{$this->nav_link[$k][1]}'>" . $this->nav_link[$k][0] . "</a>";
			} else {
				if ($this->nav_link[$k][1]) {
					$link_str .= "-><a href='{$this->nav_link[$k][1]}'>" . $this->nav_link[$k][0] . "</a>";
				} else {
					$link_str .= "->" . $this->nav_link[$k][0];
				}
			}
		}
		$this->assign("nav_link", $link_str);

	}

	function _do_headers() {
		return;
	}
 
	/*
	*说明：函数功能是把一个图像裁剪为任意大小的图像，图像不变形
	* 参数说明：输入 需要处理图片的 文件名，生成新图片的保存文件名，生成新图片的宽，生成新图片的高
	* written by smallchicken
	* time 2008-12-18
	*/
	// 获得任意大小图像，不足地方拉伸，不产生变形，不留下空白
	function resizeImage($src_file, $dst_file, $new_width, $new_height) {
		if ($new_width < 1 || $new_height < 1) {
			echo "params width or height error !";
			exit ();
		}
		if (!file_exists($src_file)) {
			echo $src_file . " is not exists !";
			exit ();
		}
		// 图像类型
		$type = exif_imagetype($src_file);
		$support_type = array (
			IMAGETYPE_JPEG,
			IMAGETYPE_PNG,
			IMAGETYPE_GIF
		);
		if (!in_array($type, $support_type, true)) {
			echo "this type of image does not support! only support jpg , gif or png";
			exit ();
		}
		//Load image
		switch ($type) {
			case IMAGETYPE_JPEG :
				$src_img = imagecreatefromjpeg($src_file);
				break;
			case IMAGETYPE_PNG :
				$src_img = imagecreatefrompng($src_file);
				break;
			case IMAGETYPE_GIF :
				$src_img = imagecreatefromgif($src_file);
				break;
			default :
				echo "Load image error!";
				exit ();
		}
		$w = imagesx($src_img);
		$h = imagesy($src_img);
		$ratio_w = 1.0 * $new_width / $w;
		$ratio_h = 1.0 * $new_height / $h;
		$ratio = 1.0;
		// 生成的图像的高宽比原来的都小，或都大 ，原则是 取大比例放大，取大比例缩小（缩小的比例就比较小了）
		if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
			if ($ratio_w < $ratio_h) {
				$ratio = $ratio_h; // 情况一，宽度的比例比高度方向的小，按照高度的比例标准来裁剪或放大
			} else {
				$ratio = $ratio_w;
			}
			// 定义一个中间的临时图像，该图像的宽高比 正好满足目标要求
			$inter_w = (int) ($new_width / $ratio);
			$inter_h = (int) ($new_height / $ratio);
			$inter_img = imagecreatetruecolor($inter_w, $inter_h);
			imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h);
			// 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
			// 定义一个新的图像
			$new_img = imagecreatetruecolor($new_width, $new_height);
			imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h);
			switch ($type) {
				case IMAGETYPE_JPEG :
					imagejpeg($new_img, $dst_file, 100); // 存储图像
					break;
				case IMAGETYPE_PNG :
					imagepng($new_img, $dst_file, 100);
					break;
				case IMAGETYPE_GIF :
					imagegif($new_img, $dst_file, 100);
					break;
				default :
					break;
			}
		} // end if 1
		// 2 目标图像 的一个边大于原图，一个边小于原图 ，先放大平普图像，然后裁剪
		// =if( ($ratio_w < 1 && $ratio_h > 1) || ($ratio_w >1 && $ratio_h <1) )
		else {
			$ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w; //取比例大的那个值
			// 定义一个中间的大图像，该图像的高或宽和目标图像相等，然后对原图放大
			$inter_w = (int) ($w * $ratio);
			$inter_h = (int) ($h * $ratio);
			$inter_img = imagecreatetruecolor($inter_w, $inter_h);
			//将原图缩放比例后裁剪
			imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h);
			// 定义一个新的图像
			$new_img = imagecreatetruecolor($new_width, $new_height);
			imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
			switch ($type) {
				case IMAGETYPE_JPEG :
					imagejpeg($new_img, $dst_file, 100); // 存储图像
					break;
				case IMAGETYPE_PNG :
					imagepng($new_img, $dst_file, 100);
					break;
				case IMAGETYPE_GIF :
					imagegif($new_img, $dst_file, 100);
					break;
				default :
					break;
			}
		} // if3
	} // end function
	//----------------- Add by 縮圖外掛 --------------------------- 
	function _resize($dest, $src, $imglib, $convert_path) {

		if (!@ is_file($src))
			return;

		$quality = 82; //----JPG 壓縮品質 

		$image_info = getimagesize($src);
		$srcSize_W = $image_info[0];
		$srcSize_H = $image_info[1];

		$img_aspect = $srcSize_W / $srcSize_H;

		if ($srcSize_H > $srcSize_W * 2)
			define(SMALL_IMAGE_HEIGHT, 100);

		if (SMALL_IMAGE_WIDTH > 0) {
			$destSize_W = SMALL_IMAGE_WIDTH;
			$destSize_H = intval($destSize_W / $img_aspect);
		} else
			if (SMALL_IMAGE_HEIGHT > 0) {
				$destSize_H = SMALL_IMAGE_HEIGHT;
				$destSize_W = intval($destSize_H * $img_aspect);
			} else {
				$destSize_W = 100;
				$destSize_H = intval($destSize_W / $img_aspect);
			}

		if ($imglib == "php") {
			//----------- With buildin php GD function -----------------------           

			$destImage = function_exists('imageCreateTrueColor') ? imageCreateTrueColor($destSize_W, $destSize_H) : imageCreate($destSize_W, $destSize_H);

			//imageAntiAlias($destImage,true); 
			//------消鋸齒演算，因看不出效果，故移除以節省時間。 

			switch ($image_info[2]) {
				case 1 : //GIF 
					$srcImage = imageCreateFromGif($src);
					imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize_W, $destSize_H, $srcSize_W, $srcSize_H);
					imagegif($destImage, $dest);
					//@copy ($src,$dest); 
					break;

				case 2 : //JPEG 
					$srcImage = imageCreateFromJpeg($src);
					//------- 進行縮圖演算--------------- 
					imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize_W, $destSize_H, $srcSize_W, $srcSize_H);
					imageJpeg($destImage, $dest, $quality);
					break;

				case 3 : //PNG 
					$srcImage = imageCreateFromPng($src);
					//------- 進行縮圖演算--------------- 
					imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize_W, $destSize_H, $srcSize_W, $srcSize_H);
					imagePng($destImage, $dest);
					break;

				default :
					return false;
					break;
			}
			if ($srcImage)
				imagedestroy($srcImage);
			if ($destImage)
				imagedestroy($destImage);

		} else {
			@ copy($src, $dest);
		}

	}
	/**
	 * 与js escape()函数 一样 加密 url 参数值
	 */
	function escape($str) {
		$str = iconv('UTF-8','GBK',$str);
		preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/", $str, $r);
		$ar = $r[0];
		foreach ($ar as $k => $v) {
			if (ord($v[0]) < 128)
				$ar[$k] = rawurlencode($v);
			else
				$ar[$k] = "%u" . bin2hex(iconv("GBK", "UCS-2", $v));
		}
		$str = join("", $ar);
		return stripcslashes(stripcslashes($str));
	}
	/**
	  * 与js unescape()函数 一样 解密 url 参数值
	  */
	function unescape($str) {
		$str = rawurldecode($str);
		preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U", $str, $r);
		$ar = $r[0];
		foreach ($ar as $k => $v) {
			if (substr($v, 0, 2) == "%u")
				$ar[$k] = iconv("UCS-2", "UTF-8", pack("H4", substr($v, -4)));
			elseif (substr($v, 0, 3) == "&#x") $ar[$k] = iconv("UCS-2", "UTF-8", pack("H4", substr($v, 3, -1)));
			elseif (substr($v, 0, 2) == "&#") {
				$ar[$k] = iconv("UCS-2", "UTF-8", pack("n", substr($v, 2, -1)));
			}
		}
		return join("", $ar);
	}
	function showerror($errstr = "Undefined error!") {
		echo "<script language=javascript>alert('$errstr');location='javascript:history.go(-1);';</script>";
		exit ();
	}
	function showMsg($msgstr,$toUrl=null) {
		if($toUrl)
		{
			echo "<script language=javascript>alert('$msgstr');window.location='$toUrl';</script>";
		}
		else
		{
			echo "<script language=javascript>alert('$msgstr');</script>";
		}
	}
/**
 * 删除指定目录下的所有文件
 *
 * @param String $dir  要进行操作的路径
 * 适合范围，只有用于文件夹内不存在子文件夹的情况下
 * 来源  DZ
 * 小佳(www.phpcina.cn)  整理 于 2006-06-26 
 */
function dir_clear($dir) {
    $directory = dir($dir);                //创建一个dir类(PHP手册上这么说的)，用来读取目录中的每一个文件
    while($entry = $directory->read()) {   //循环每一个文件,并取得文件名$entry
        $filename = $dir.'/'.$entry;       //取得完整的文件名，带路径的
        if(is_file($filename)) {           //如果是文件，则执行删除操作
            @unlink($filename);
        }
    }
    $directory->close();                   //关闭读取目录文件的类
     
}   
//$sourcestr 是要处理的字符串
//$cutlength 为截取的长度(即字数)
function cut_str($sourcestr,$cutlength)
{
   $returnstr='';
   $i=0;
   $n=0;
   $str_length=strlen($sourcestr);//字符串的字节数
   while (($n<$cutlength) and ($i<=$str_length))
   {
      $temp_str=substr($sourcestr,$i,1);
      $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
      if ($ascnum>=224)    //如果ASCII位高与224，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符         
         $i=$i+3;            //实际Byte计为3
         $n++;            //字串长度计1
      }
      elseif ($ascnum>=192) //如果ASCII位高与192，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
         $i=$i+2;            //实际Byte计为2
         $n++;            //字串长度计1
      }
      elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,1);
         $i=$i+1;            //实际的Byte数仍计1个
         $n++;            //但考虑整体美观，大写字母计成一个高位字符
      }
      else                //其他情况下，包括小写字母和半角标点符号，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,1);
         $i=$i+1;            //实际的Byte数计1个
         $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
      }
   }
         if ($str_length>$cutlength){
          $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
      }
    return $returnstr;

}
function postData($data, $url)
{
	$o="";
	foreach ($data as $k=>$v)
	{
    	$o.= "$k=".urlencode($v)."&";
	}
	$data=substr($o,0,-1);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_URL,$url);
	//为了支持cookie
	curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$result = curl_exec($ch); 	
	//return $result;
}

function is_email($email)
{
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-]+(\.\w+)+$/", $email);
}

function is_url($str)
{
  return preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $str);
 }

function is_mobile($str)
{
  return preg_match("/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/", $str);
}
function formatTimeStamp($timeStamp,$format = "Y-m-d H:i")
{
	return date($format,$timeStamp);
}
function passportEncrypt($txt, $key) {
	srand ( ( double ) microtime () * 1000000 );
	$encrypt_key = md5 ( rand ( 0, 32000 ) );
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen ( $txt ); $i ++) {
		$ctr = $ctr == strlen ( $encrypt_key ) ? 0 : $ctr;
		$tmp .= $encrypt_key [$ctr] . ($txt [$i] ^ $encrypt_key [$ctr ++]);
	}
	return base64_encode ( $this->passportKey ( $tmp, $key ) );
}

function passportDecrypt($txt, $key) {
	$txt = $this->passportKey ( base64_decode ( $txt ), $key );
	$tmp = '';
	for($i = 0; $i < strlen ( $txt ); $i ++) {
		$md5 = $txt [$i];
		$tmp .= $txt [++ $i] ^ $md5;
	}
	return $tmp;
}

function passportKey($txt, $encrypt_key) {
	$encrypt_key = md5 ( $encrypt_key); 
	$ctr = 0; 
	$tmp = ''; 
	for($i = 0; $i < strlen($txt); $i++) { 
	$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; 
	$tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; 
} 
return $tmp; 
} 
}

class session {
	var $ip_address;
	var $time_now;
	var $session_user_id;
	var $session_id;
	var $session_dead_id;
	var $location;
	var $seller = array ();

	function authorise() {
		global $BIZ, $INCOME;

		//--------------------------------------------
		//  ip banned check 
		//--------------------------------------------

		//--------------------------------------------

		$this->ip_address = $INCOME['IP_ADDRESS'];
		$this->time_now = time();

		$cookie = array ();
		$cookie['session_id'] = $BIZ->my_getcookie('session_id');
		$cookie['seller_id'] = $BIZ->my_getcookie('seller_id');
		$cookie['pass_hash'] = $BIZ->my_getcookie('pass_hash');

		if ($cookie['session_id']) {
			$this->get_session($cookie['session_id']);
			$BIZ->session_type = 'cookie';
		}
		elseif ($INCOME['s']) {
			$this->get_session($INCOME['s']);
			$BIZ->session_type = 'url';
		} else {

			$this->session_id = 0;
		}
		//-------------------------------------------------								  
		// Do we have a valid session ID?
		//-------------------------------------------------
		if ($this->session_id) {
			// We've checked the IP addy and browser, so we can assume that this is
			// a valid session.
			if (($this->session_user_id != 0) and (!empty ($this->session_user_id))) {
				// It's a seller session, so load the seller.

				$this->load_seller($this->session_user_id);
				// Did we get a seller?

				if ((!$this->seller['seller_id']) or ($this->seller['seller_id'] == 0)) {
					$this->unload_seller();
					$this->update_guest_session();
				} else {
					$this->update_seller_session();
				}
			} else {
				$this->update_guest_session();
			}

		} else {
			// We didn't have a session, or the session didn't validate

			// Do we have cookies stored?

			if ($cookie['seller_id'] != "" and $cookie['pass_hash'] != "") {
				$this->load_seller($cookie['seller_id']);

				if ((!$this->seller['seller_id']) or ($this->seller['seller_id'] == 0)) {
					$this->unload_seller();
					$this->create_guest_session();
				} else {
					if ($this->seller['seller_password'] == $cookie['pass_hash']) {
						$this->create_seller_session();
					} else {
						$this->unload_seller();
						$this->create_guest_session();
					}
				}
			} else {
				$this->create_guest_session();
			}
		}

		//-------------------------------------------------
		// Set a session ID cookie
		//-------------------------------------------------
		$BIZ->my_setcookie("session_id", $this->session_id, -1);

		return $this->seller;

	}

	function load_seller($seller_id = 0) {
		global $DB, $BIZ, $INCOME;

		$seller_id = intval($seller_id);

		if ($seller_id != 0) {

			$DB->db_query("SELECT * FROM biz_seller  WHERE seller_id='$seller_id'");

			if ($DB->db_fetch_num()) {
				$this->seller = $DB->db_fetch_row();
			}

			//-------------------------------------------------
			// Unless they have a seller id, log 'em in as a guest
			//-------------------------------------------------

			if (($this->seller['seller_id'] == 0) or (empty ($this->seller['seller_id']))) {
				$this->unload_seller();
			}
		}

		unset ($seller_id);
	}

	//+-------------------------------------------------
	// Remove the users cookies
	//+-------------------------------------------------

	function unload_seller() {
		global $DB, $BIZ, $INCOME;

		// Boink the cookies

		$BIZ->my_setcookie("seller_id", "0", -1);
		$BIZ->my_setcookie("pass_hash", "0", -1);

		$this->seller['seller_id'] = 0;
		$this->seller['seller_logaccount'] = "";
		$this->seller['seller_password'] = "";

	}

	//-------------------------------------------
	// Updates a current session.
	//-------------------------------------------

	function update_seller_session() {
		global $DB, $INCOME;

		// Make sure we have a session id.

		if (!$this->session_id) {
			$this->create_seller_session();
			return;
		}

		if (empty ($this->seller['seller_id'])) {
			$this->unload_seller();
			$this->create_guest_session();
			return;
		}

		$db_str = $DB->db_compile_update_fields(array (
			'seller_logaccount' => $this->seller['seller_logaccount'],
			'seller_id' => intval($this->seller['seller_id']),
			'running_time' => $this->time_now,
			'location' => $INCOME['act'] . "," . $INCOME['p'] . "," . $INCOME['code']
		));

		$DB->db_query("UPDATE biz_session SET $db_str WHERE id='{$this->session_id}'");

	}

	//--------------------------------------------------------------------

	function update_guest_session() {
		global $DB, $BIZ, $INCOME;

		// Make sure we have a session id.

		if (!$this->session_id) {
			$this->create_guest_session();
			return;
		}

		$query = "UPDATE biz_session SET seller_logaccount='',seller_id='0' ";
		$query .= ", running_time='" . $this->time_now . "', location='" . $INCOME['act'] . "," . $INCOME['code'] . "' ";
		$query .= "WHERE id='" . $this->session_id . "'";

		// Update the database

		$DB->db_query($query);
	}

	//-------------------------------------------
	// Get a session based on the current session ID
	//-------------------------------------------

	function get_session($session_id = "") {
		global $DB, $CONF, $BIZ;

		$result = array ();

		$query = "";

		$session_id = preg_replace("/([^a-zA-Z0-9])/", "", $session_id);

		if ($session_id) {

			$DB->db_query("SELECT id, seller_id, running_time, location FROM biz_session WHERE id='" . $session_id . "' and ip_address='" . $this->ip_address . "'" . $query);

			if ($DB->db_fetch_num() != 1) {
				// Either there is no session, or we have more than one session..

				$this->session_dead_id = $session_id;
				$this->session_id = 0;
				$this->session_user_id = 0;
				return;
			} else {
				$result = $DB->db_fetch_row();

				if ($result['id'] == "") {
					$this->session_dead_id = $session_id;
					$this->session_id = 0;
					$this->session_user_id = 0;
					unset ($result);
					return;
				} else {
					$this->session_id = $result['id'];
					$this->session_user_id = $result['seller_id'];
					$this->last_click = $result['running_time'];
					$this->location = $result['location'];
					unset ($result);
					return;
				}
			}
		}
	}

	//-------------------------------------------
	// Creates a seller session.
	//-------------------------------------------

	function create_seller_session() {
		global $DB, $CONF, $BIZ, $INCOME;

		if ($this->seller['seller_id']) {
			//---------------------------------
			// Remove the defunct sessions
			//---------------------------------

			$CONF['session_expiration'] = $CONF['session_expiration'] ? (time() - $CONF['session_expiration']) : (time() - 3600);

			$DB->db_query("DELETE FROM biz_session WHERE running_time < {$CONF['session_expiration']} or seller_id='" . $this->seller['seller_id'] . "'");

			$this->session_id = md5(uniqid(microtime()));

			//---------------------------------
			// Insert the new session
			//---------------------------------

			$DB->db_query("INSERT INTO biz_session (id, seller_logaccount, seller_id, ip_address,running_time, location) " .
			"VALUES ('" . $this->session_id . "', '" . $this->seller['seller_logaccount'] . "', '" . $this->seller['seller_id'] . "', '" . $this->ip_address . "', '" . $this->time_now . "',''" .
			")");
			/// for debug
		} else {
			$this->create_guest_session();
		}
	}

	//--------------------------------------------------------------------

	function create_guest_session() {
		global $DB, $CONF, $BIZ;

		//---------------------------------
		// Remove the defunct sessions
		//---------------------------------

		if (($this->session_dead_id != 0) and (!empty ($this->session_dead_id))) {
			$extra = " or id='" . $this->session_dead_id . "'";
		} else {
			$extra = "";
		}

		$CONF['session_expiration'] = $CONF['session_expiration'] ? (time() - $CONF['session_expiration']) : (time() - 3600);

		$DB->db_query("DELETE FROM biz_session WHERE running_time < {$CONF['session_expiration']} or ip_address='" . $this->ip_address . "'" . $extra);

		$this->session_id = md5(uniqid(microtime()));

		//---------------------------------
		// Insert the new session
		//---------------------------------

		$DB->db_query("INSERT INTO biz_session (id, seller_logaccount, seller_id, ip_address, running_time, location) " .
		"VALUES ('" . $this->session_id . "', '', '0', '" . $this->ip_address . "', '" . $this->time_now . "', '' " . ")");

	}
}

class cache {

	function DB_Cache($sql) {
		global $DB;
		$bizdb = array ();
		$query = $DB->db_query($sql);
		while ($rt = $DB->db_fetch_row($query, MYSQL_NUM)) {
			$bizdb[] = $rt;
		}
		return $this->array_export($bizdb);
	}

	function array_export($array, $c = 1, $t = '', $var = '') {
		$c && $var = "array(\r\n";
		$t .= "  ";
		if (is_array($array)) {
			foreach ($array as $key => $value) {
				$var .= "$t'" . addslashes($key) . "'=>";
				if (is_array($value)) {
					$var .= "array(\r\n";
					$var = $this->array_export($value, 0, $t, $var);
					$var .= "$t),\r\n";
				} else {
					$var .= "'" . addslashes($value) . "',\r\n";
				}
			}
		}
		if ($c) {
			$var .= ")";
		}
		return $var;
	}

	function write_cache($filename, $data, $method = "rb+", $iflock = 1) {
		touch($filename);
		$handle = fopen($filename, $method);
		if ($iflock) {
			flock($handle, LOCK_EX);
		}
		fputs($handle, $data);
		if ($method == "rb+")
			ftruncate($handle, strlen($data));
		fclose($handle);
	}
}
?>